<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-form-item>
          <el-select v-model="filters.shopid" placeholder="所属店铺" style="width:215px">
            <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="filters.startTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            value-format="yyyy-MM-dd"
            @change="startTime"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="filters.endTime"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            start-placeholder="结束时间"
            @change="endTime"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model.number="filters.startMoney"
            auto-complete="off"
            type="age"
            placeholder="请输入所需金额"
          ></el-input>
        </el-form-item>-
        <el-form-item>
          <el-input
            v-model.number="filters.endMoney"
            auto-complete="off"
            type="age"
            placeholder="请输入所需金额"
          ></el-input>
        </el-form-item>

        <el-row>
          <el-form-item>
            <el-select v-model="filters.status" placeholder="状态" style="width:215px">
              <el-option
                v-for="item in statusList"
                :key="item.val"
                :label="item.name"
                :value="item.val"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.number="filters.startIntegral"
              auto-complete="off"
              type="age"
              placeholder="请输入所需积分"
              style="width:160px"
            ></el-input>
          </el-form-item>
          <span>-</span>
          <el-form-item>
            <el-input
              v-model.number="filters.endIntegral"
              auto-complete="off"
              type="age"
              placeholder="请输入所需积分"
              style="width:165px"
            ></el-input>
          </el-form-item>

        </el-row>
        <el-row>
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" @click="resetForm('filters')" />
          </el-form-item>
        </el-row>

        <el-row class="gongnengList">
          <el-form-item>
            <el-button type="primary" plain @click="handleAdd">新增特殊商品兑换配置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="updateStatus(1)">启用</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="updateStatus(0)">停用</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain>关联活动商品</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="userDialog">关联用户</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="handleEdit">修改兑换配置</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o" @click="downloadExcel"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog
        ref="tableColumnFilterDialog"
        :columns="columns"
        @handleFilterColumns="handleFilterColumns"
      ></table-column-filter-dialog>
    </div>
    <!--表格内容栏-->
    <cy-table
      :height="350"
      :data="pageResult"
      :columns="filterColumns"
      @findPage="findPage"
      :showOperation="true"
      :showEditOperation="false"
      :showBatchDelete="true"
      @handleDelete="handleDelete"
      @selectionChange="selectionChange"
      ref="CyTable"
    ></cy-table>

    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="40%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="120px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-form-item label="所属店铺" prop="shop_id">
          <el-select
            v-model="dataForm.shop_id"
            placeholder="请选择所属店铺"
            style="width:100%;"
            auto-complete="off"
          >
            <el-option
              v-for="item in shopList"
              :key="item.id+''"
              :label="item.name"
              :value="item.id+''"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所需金额" prop="money">
          <el-input
            v-model.number="dataForm.money"
            auto-complete="off"
            type="age"
            placeholder="请输入所需金额"
          ></el-input>
        </el-form-item>
        <el-form-item label="所需积分" prop="integral">
          <el-input
            v-model.number="dataForm.integral"
            auto-complete="off"
            type="age"
            placeholder="请输入所需积分"
          ></el-input>
        </el-form-item>
        <el-form-item label="有效时间" prop="time">
          <el-date-picker
            v-model="dataForm.time"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="生效时间"
            end-placeholder="失效时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="right"
            @change="changeTime"
            style="width:100%;"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>

    <!-- 关联用户 -->
    <el-dialog
      :title="'关联用户'"
      width="90%"
      :visible.sync="userDialogModel"
      :close-on-click-modal="false"
    >
      <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
        <!--表格显示列界面-->
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columnsUser"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </div>
      <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
        <el-form :inline="true" :model="filtersUser" :size="size" ref="filtersUser">
          <el-row>
            <el-form-item>
              <el-input
                v-model="filtersUser.username"
                auto-complete="off"
                type="text"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="filtersUser.telephone"
                auto-complete="off"
                type="text"
                placeholder="请输入用户手机号"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item>
              <kt-button
                icon="fa fa-search"
                :label="$t('action.search')"
                type="primary"
                @click="findPageUser(null)"
              />
            </el-form-item>
            <el-form-item>
              <kt-button icon="fa fa-refresh" :label="$t('action.reset')"
                type="primary"
                @click="resetFormUser('filtersUser')"
              />
            </el-form-item>
          </el-row>

          <el-row class="gongnengList">
            <el-form-item>
              <el-button type="primary" plain @click="associatedUser">关联用户</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <!--表格内容栏-->
      <!-- <cy-table
      :height="350"
      :data="pageResult"
      :columns="filterColumnsUser"
      @findPage="findPageUser"
      :showOperation="false"
      :showEditOperation="false"
      :showBatchDelete="false"
      :showDeleteOperation="false"
      ref="CyTable"
      ></cy-table>-->
      <div class="alertUserList">
        <cy-table
          :height="350"
          :data="pageResult"
          :columns="filterColumnsUser"
          @findPage="findPageUser"
          :showOperation="false"
          :showEditOperation="false"
          :showBatchDelete="true"
          @handleDelete="handleDelete"
          @selectionChange="selectionChangeUser"
          ref="CyTable"
        ></cy-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CyTable from "@/views/Core/CyTable";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
export default {
  components: {
    CyTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      size: "small",
      shopList: [],
      statusList: [
        {
          val: "0",
          name: "失效"
        },
        {
          val: "1",
          name: "有效"
        }
      ],
      filters: {
        startTime: "",
        endTime: "",
        t: "marketSpecial",
        shopid: "",
        startMoney: "",
        endMoney: "",
        startIntegral: "",
        endIntegral: "",
        status: ""
      },
      filtersUser: {
        t: "member",
        username: "",
        telephone: ""
      },
      columns: [
        { prop: "shopname", label: "所属商铺", minWidth: 100 },
        { prop: "money", label: "所需金额", minWidth: 80 },
        { prop: "integral", label: "所需积分", minWidth: 80 },
        { prop: "start", label: "开始时间", minWidth: 80 },
        { prop: "end", label: "结束时间", minWidth: 80 },
        { prop: "statusval", label: "是否有效", minWidth: 80 },
        { prop: "create_time", label: "创建时间", minWidth: 80 },
        { prop: "creatorname", label: "创建人", minWidth: 80 },
        { prop: "update_time", label: "修改时间", minWidth: 80 },
        { prop: "updatorname", label: "修改人", minWidth: 80 }
      ],
      columnsUser: [
        { prop: "username", label: "用户名", minWidth: 100 },
        { prop: "telephone", label: "手机号码", minWidth: 80 },
        { prop: "company", label: "所属公司", minWidth: 80 },
        { prop: "nickname", label: "昵称", minWidth: 80 },
        { prop: "register_type", label: "注册类型", minWidth: 80 },
        { prop: "register_time", label: "注册时间", minWidth: 80 },
        { prop: "remainder", label: "会员余额", minWidth: 80 },
        { prop: "gradename", label: "会员等级", minWidth: 80 },
        { prop: "integration", label: "会员积分", minWidth: 80 },
        { prop: "status_alias", label: "状态", minWidth: 80 }
      ],
      filterColumns: [],
      filterColumnsUser: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {},
      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      userDialogModel: false, //关联用户弹窗

      editLoading: false,
      dataForm: {
        shop_id: "",
        money: "",
        integral: "",
        time: ""
      },
      dataFormRules: {
        // shop_id: [{ required: true, message: "请选择所属店铺", trigger: "blur" },{ type: 'number', message: '限制人数必须为数字值'}],
        shop_id: [
          { required: true, message: "请选择所属店铺", trigger: "change" }
        ],
        money: [
          { required: true, message: "请输入所需金额", trigger: "blur" },
          { type: "number", message: "所需金额必须为数字值" }
        ],
        integral: [
          { required: true, message: "请输入所需积分", trigger: "blur" },
          { type: "number", message: "所需积分必须为数字值" }
        ],
        time: [{ required: true, message: "请选择有效时间", trigger: "blur" }]
      },
      selections: [],
      selectionsUser: []
    };
  },
  methods: {
    // 获取分页数据
    findPage: function(data) {
      this.$refs.CyTable.findPage(this.filters);
    },
    findPageUser: function(data) {
      this.$refs.CyTable.findPage(this.filtersUser);
    },

    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    resetFormUser(formName) {
      this.filtersUser.username = "";
      this.filtersUser.telephone = "";
      this.findPageUser();
    },
    resetForm(formName) {
      this.filters = JSON.parse(JSON.stringify(this.defaultFilters));
      this.findPage();
      // this.$refs["filters"].resetFields();
      // if (this.$refs[formName] != undefined) {
      //   this.$refs[formName].resetFields();
      //   this.findPage();
      // }
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      var temp = [];

      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    initColumnsUser: function() {
      var temp = [];
      $.each(this.columnsUser, function(key, val) {
        temp.push(val);
      });
      this.filterColumnsUser = temp;
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let filename = "系统参数下载";
          this.$refs.CyTable.exportData(
            this.filters,
            this.filterColumns,
            filename
          );
        })
        .catch(() => {});
    },
    handleDelete: function(data) {
      let this_ = this;
      console.log(data.params);
      let paramsList = data.params;
      let idList = [];
      for (let index in paramsList) {
        idList.push(paramsList[index].id);
      }
      let params = {
        ids: idList.join(","),
        t: "marketSpecial"
      };
      this.utils.request.deleteUserInfo(params, function(res) {
        if (res.code == "0000") {
          this_.$message({ message: "操作成功", type: "success" });
          this_.findPage(null);
        } else {
          this_.$message({ message: "操作失败, " + res.msg, type: "error" });
        }
      });
    },
    //查询所有店铺
    queryShop() {
      let that = this;
      this.utils.request.queryShop({}, res => {
        that.shopList = res.data;
      });
    },
    startTime(e) {
      console.log(e);
      this.filters.startDate = e[0];
      this.filters.endDate = e[1];
    },
    endTime(e) {
      console.log(e);
      this.filters.startTime = e[0];
      this.filters.endTime = e[1];
    },
    changeTime(e) {
      if (e != null) {
        console.log(e);
        this.dataForm.start = e[0];
        this.dataForm.end = e[1];
      }
    },
    // 显示新增界面
    handleAdd: function() {
      this.editDialogVisible = true;
      this.operation = true;
      //第一次点击不需要清空表单
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });
      console.log(this.dataForm);
    },
    // 显示编辑界面
    handleEdit: function(params) {
      //获取选中的
      let boo = this.selectCheck();
      if (!boo) {
        return false;
      }
      //选择了一条数据
      this.editDialogVisible = true;
      this.operation = false;
      this.$nextTick(function() {
        this.dataForm = Object.assign({}, this.selections[0]);
        this.dataForm.shop_id = this.dataForm.shop_id + "";
        this.dataForm.time = [this.dataForm.start, this.dataForm.end];
      });
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.dataForm);

            params.t = "marketSpecial";
            var this_ = this;
            this.utils.request.editInfo(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });

                this_.$refs["dataForm"].resetFields();

                this_.editDialogVisible = false;

                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },
    selectionChange(e) {
      this.selections = e.selections;
      console.log(this.selections);
    },
    selectionChangeUser(e) {
      this.selectionsUser = e.selections;
      console.log(this.selectionsUser);
    },
    // 更新状态 启用 停用
    updateStatus(type) {
      let boo = this.selectCheck();
      if (!boo) {
        return false;
      }
      let status = this.selections[0].status;
      let id = this.selections[0].id;
      if (status === type) {
        this.$message({
          message: "当前状态和修改状态一致，无需重复修改",
          type: "info"
        });
        return false;
      }
      status = status == 1 ? 0 : 1;
      let that = this;
      that.utils.request.editUserInfo(
        { t: that.filters.t, id: id, status: status },
        res => {
          that.findPage();
          if (status == 0) {
            that.$message({ message: "停用成功", type: "success" });
          } else {
            that.$message({ message: "启用成功", type: "success" });
          }
        }
      );
    },
    //关联用户弹窗
    userDialog() {
      let boo = this.selectCheck();
      if (!boo) {
        return false;
      }
      this.userDialogModel = true;
      this.initColumnsUser();
    },
    // 关联用户
    associatedUser() {
      let boo = this.selectCheckUser();
      if (!boo) {
        return false;
      }
      //获取第一个
      let ids = this.selectionsUser.map(item => item.id).toString();
      //选择的兑换配置
      let sele = this.selections[0];
      let that = this;
      console.log(ids);
      that.utils.request.addMarketMember(
        { t: "marketProduct", ids: ids, type: "pro", marketid: sele.id },
        res => {
          that.userDialogModel = false;
          that.$message({ message: "关联用户成功", type: "success" });
          // that.findPage();
        }
      );
    },
    selectCheck() {
      console.log(this.selections);
      if (this.selections.length < 1) {
        this.$message({ message: "必须要选择一条数据", type: "warning" });
        return false;
      }
      if (this.selections.length > 1) {
        this.$message({ message: "只能选择一条数据", type: "warning" });
        return false;
      }
      return true;
    },
    selectCheckUser() {
      console.log(this.selectionsUser);
      if (this.selectionsUser.length < 1) {
        this.$message({ message: "必须要选择一条数据", type: "warning" });
        return false;
      }
      return true;
    }
  },
  mounted() {
    this.queryShop();
    this.initColumns();
    this.defaultFilters = JSON.parse(JSON.stringify(this.filters));
  }
};
</script>

<style scoped>
.gongnengList .el-button--mini {
  padding: 10px 18px;
  font-size: 13px;
}
.el-button--primary.is-plain {
  color: #2F4554;
  background: #ffffff;
  border-color: #b3d8ff;
}
.el-button--primary:hover {
  color: #fff;
  background-color: #2F4554;
  border-color: #2F4554;
}
</style>
